package com.ibm.psbc.cloud.common.contextcarrier.springmvc;

import java.util.Map;

import javax.inject.Inject;

import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.core.MethodParameter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import com.ibm.psbc.cloud.common.contextcarrier.ContextUtils;
import com.ibm.psbc.cloud.common.contextcarrier.feign.ContextCarryInterceptor;

import lombok.extern.slf4j.Slf4j;

/**
 * Spring mvc rest, 服务结束后，把context中相关信息放到header传递回去
 * @author johnny
 *
 *
 * @param <T> Context class
 */
@Slf4j
@ControllerAdvice
public class Context2HeaderAdvice<T> implements ResponseBodyAdvice<Object> {
	@Inject
	private ContextUtils<T> contextUtils;
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        HttpHeaders headers = response.getHeaders();
        log.trace("Service END...");
        Map<String, String> contextData = contextUtils.context2Map();
        for (Map.Entry<String, String> ent : contextData.entrySet()) {
        	headers.add(ent.getKey(), ent.getValue());
		}
        return body;
    }
}